/***

    KunGang - Simple Video Editor
    Copyright (C) 2020  SUmoon.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

***/

#include "newproj.h"

#include <QGridLayout>
#include <QLabel>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QFileDialog>
#include <QPushButton>
#include <QMessageBox>
#include <QDebug>
#include <QSignalMapper>


#include "project/proxygenerator.h"
#include "project/footage.h"
#include "ui/mainwindow.h"
#include "global/global.h"
#include "global/path.h"
#include "global/config.h"

NewProjDialog::NewProjDialog(QWidget *parent, bool showRecents) :
  QDialog(parent)
{
  HIDE_DIALOG_QUESTION_MARK

  new_proj_layouted = false;
  // set dialog title
  if(showRecents)
    setWindowTitle(tr("Project"));
  else
    setWindowTitle(tr("create new project"));
  line = 0;
  //bool showRecents = true;
  //bool showNewProj = false;
 // set up dialog's layout
  this->setFixedWidth(400);

  QGridLayout* layout = new QGridLayout(this);
  if(showRecents)
    {

      layout->addWidget(new QLabel(tr("Recent projects"),this), line,0,1,4);
      line ++;
      QPushButton *spliter1 = new QPushButton("", this);
      spliter1->setFocusPolicy(Qt::NoFocus);
      spliter1->setMaximumHeight(1);
      spliter1->setBackgroundRole(QPalette::Text);
      layout->addWidget(spliter1, line, 0,1,4);
      line ++;         
      int maxRecent = 5;
      int count =0;
      QFile f(olive::Global->get_recent_project_list_file());
      if (f.exists() && f.open(QFile::ReadOnly | QFile::Text)) {
        QTextStream text_stream(&f);
        while (true && maxRecent > 0) {
          QString linestr = text_stream.readLine();
          if (linestr.isNull()) {
            break;
          } else {
            QFileInfo fi(linestr);
            QPushButton* rproj = new QPushButton(fi.fileName(), this);
            rproj->setProperty("recentProjIdx", count);
            connect(rproj, SIGNAL(clicked(bool)), this, SLOT(open_recent_proj()));
            
            count ++;
            layout->addWidget(rproj,line,1, 1, 2);
            line ++;
            maxRecent --;
          }
        }
        f.close();
      }
      if(count == 0)
      {
        layout->addWidget(new QLabel(tr("none"),this), line,0,1,1);
        line ++;
      } 
    QPushButton *spliter = new QPushButton("", this);
    spliter->setFocusPolicy(Qt::NoFocus);
    spliter->setMaximumHeight(1);
    spliter->setBackgroundRole(QPalette::Text);
    layout->addWidget(spliter, line, 0,1,4);
    line ++;      
      QPushButton* otherProj = new QPushButton(tr("open other project"),this);
      connect(otherProj, SIGNAL(clicked(bool)),this, SLOT(open_project()));
      layout->addWidget(otherProj, line,0,1,2);
      //line ++;

      QPushButton* newproj = new QPushButton(tr("create new project"),this);
      connect(newproj, SIGNAL(clicked(bool)), this, SLOT(layout_new_proj()));
      layout->addWidget(newproj, line, 2, 1, 2);
      line ++;
    }
 
  if(!showRecents)
  {
    layout_new_proj();
  }
}
void NewProjDialog::open_recent_proj()
{
  int idx = sender()->property("recentProjIdx").toInt();
  olive::Global->open_recent(idx);
  QDialog::accept();
}
void NewProjDialog::open_project()
{
   bool opened = olive::Global->OpenProject();
   if(opened)
   {
       QDialog::accept();
   }
}
void NewProjDialog::accept() {
 
 QString fn = proj_name_edit->text();

 if(fn.isEmpty())
 {
   QMessageBox::information(this, tr("project name"), tr("Project name cannot be empty"));
   return;
 }
 if (!fn.endsWith(".kgp", Qt::CaseInsensitive)) {
      fn += ".kgp";
    }
 QDir  dir(custom_location);
 bool result = olive::Global->save_project_to_file(dir.absoluteFilePath(fn));
 if(result)
  {
    olive::CurrentConfig.prefered_project_path = custom_location;
    QDialog::accept();
  }
}
void NewProjDialog::layout_new_proj()
{

    if(new_proj_layouted)
    {
      //proj_name_edit.setFocus();
      return;
    }
    QGridLayout* layout = (QGridLayout*)this->layout();
    layout->addWidget(new QLabel(tr("Project Name:"), this), line, 0,1,1);
    proj_name_edit = new QLineEdit(this);
    layout->addWidget(proj_name_edit,line, 1,1,3); 

    line ++;


    customize_btn = new QPushButton(tr("customize"), this);
    connect(customize_btn, SIGNAL(clicked(bool)), this, SLOT(location_changed()));
    layout->addWidget(customize_btn, line,0,1,1);

    proj_location_edit = new QLineEdit(this);
    proj_location_edit->setReadOnly(true);
    QString p = olive::CurrentConfig.prefered_project_path;
    if(p.isEmpty())
      p = get_doc_path();
    custom_location = p;
    proj_location_edit->setText(p);
    layout->addWidget(proj_location_edit, line,1,1,3);

    line ++;
 
    // set up dialog buttons
    QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
    buttons->setCenterButtons(true);
    layout->addWidget(buttons, line, 0, 1, 2);
    connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttons, SIGNAL(rejected()), this, SLOT(reject()));
    new_proj_layouted = true;
}
void NewProjDialog::location_changed() {
    // if the user picked a custom location, ask which directory
    QString s = QFileDialog::getExistingDirectory(this);

    if (!s.isEmpty())  {
      proj_location_edit->setText(s);
      custom_location = s;
    }

}
